package com.wisedu.mobile.manage.controller;

import com.wisedu.mobile.auth.service.impl.v1.db.SysRoleServiceImpl;
import com.wisedu.mobile.auth.service.impl.v1.db.SysUserServiceImpl;
import com.wisedu.mobile.common.AjaxResult;
import com.wisedu.mobile.common.BaseController;
import com.wisedu.mobile.common.domain.SysRole;
import com.wisedu.mobile.common.domain.SysUser;
import org.nutz.dao.entity.Record;
import org.nutz.lang.Lang;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: hj
 * @Date: 2020/3/24 下午4:28
 */
@RestController
@RequestMapping("/manage/sys/user")
public class SysUserController extends BaseController<SysUser> {

    @Autowired
    SysUserServiceImpl sysUserService;

    @Autowired
    SysRoleServiceImpl sysRoleService;

    @PostMapping("tree")
    public AjaxResult tree(String userid) {
        List<SysRole> res = new ArrayList<>();
        List<Record> records = sysRoleService.selectRoleByUser(userid);
        for (Record r : records) {
            res.add(Lang.map2Object(r, SysRole.class));
        }
        return AjaxResult.success(res);
    }

    @PostMapping("saveUserRole")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult saveRoleMenu(String userid, String roleIdList) {
        SysUser user = sysUserService.fetch(userid);
        sysUserService._clearLinks(user, "roles");
        String[] roleids = roleIdList.split(",");
        List<SysRole> roles = new ArrayList<>();
        for (String roleid : roleids) {
            SysRole role = new SysRole();
            role.setId(roleid);
            roles.add(role);
        }
        user.setRoles(roles);
        sysUserService.insertRelation(user, "roles");
        return AjaxResult.success();
    }
}
